<template>
  <div class="comment-container">
    <el-card class="comment-card">
      <template #header>
        <div class="card-header">
          <span>评论</span>
        </div>
      </template>

      <div v-if="total == 0" class="comment-count">
        <h3>暂无评论</h3>
      </div>

      <div v-loading="loading">
        <!-- 评论列表 -->
        <div v-for="item in commentList" :key="item.commentId" class="comment-item">
          <div class="user-info">
            <el-avatar :src="getAvatarUrl(item.authorEmail)" class="avatar"
                       @click="handleAvatarClick(item.authorWebsite)"/>
            <div class="meta">
              <div class="floor-tag">
                <el-tag type="primary" effect="light" class="tag">
                  #{{ item.floor }}楼
                </el-tag>
                <el-tag v-show="item.parentFloor != null" type="success" effect="light" class="tag">
                  回复 #{{ item.parentFloor }}楼
                </el-tag>
              </div>
              <div class="time">{{ $filters.timeFilter(item.createTime) }}</div>
            </div>
          </div>

          <!-- 评论内容 -->
          <el-card class="comment-content" shadow="hover" @click="HuiFu(item.commentId, item.floor)">
            {{ item.content }}
          </el-card>
        </div>

        <!-- 分页 -->
        <div class="pagination-container" v-if="total != 0">
          <el-pagination background layout="prev, pager, next" :total="total"
                         :current-page="queryParams.pageNum" @current-change="handleCurrentChange"/>
        </div>
      </div>

      <template #footer>
        <!-- 评论表单 -->
        <div id="commentForm" class="comment-form">
          <el-form :model="fromNode" :rules="rules" ref="formRef" label-width="80px">
            <el-row :gutter="20">
              <el-col :md="8" :sm="12" :xs="24">
                <el-form-item prop="authorEmail" label="邮箱">
                  <el-input v-model="fromNode.authorEmail" placeholder="请输入您的邮箱" clearable/>
                </el-form-item>
              </el-col>
              <el-col :md="8" :sm="12" :xs="24">
                <el-form-item prop="authorWebsite" label="网站">
                  <el-input v-model="fromNode.authorWebsite" placeholder="请输入您的网站" clearable/>
                </el-form-item>
              </el-col>
              <el-col :md="6" :sm="24" :xs="24">
                <div class="reply-tag">
                  <el-tag v-show="fromNode.parentId != null" closable type="success" effect="dark"
                          @close="queryNo()">
                    回复 #{{ fromNode.parentFloor }}楼
                  </el-tag>
                </div>
              </el-col>
            </el-row>

            <el-form-item prop="content" label-width="0">
              <el-input v-model="fromNode.content" placeholder="请输入您的评论内容" :rows="4" type="textarea"
                        resize="none" clearable/>
            </el-form-item>

            <el-form-item label="验证码" prop="captcha">
              <div class="captcha-container">
                <el-input v-model="userCaptchaAnswer" placeholder="请输入计算结果" class="captcha-input"/>
                <span class="captcha-question">{{ captchaQuestion }}</span>
                <el-button type="text" icon="RefreshRight" @click="generateCaptcha"
                           class="refresh-captcha">
                  换一个
                </el-button>
              </div>
            </el-form-item>

            <div class="form-footer">
              <el-button type="primary" @click="submit" :disabled="countdown > 0" :loading="countdown > 0"
                         class="submit-btn">
                {{ countdown > 0 ? `请等待 ${countdown} 秒` : '提交评论' }}
              </el-button>

              <p class="tip-text">评论区提示：点击头像可以访问评论者的网站，点击评论内容可以回复该评论。</p>
            </div>
          </el-form>
        </div>
      </template>
    </el-card>
  </div>
</template>

<script setup>
import {ref, defineProps, reactive, h, onMounted, onUnmounted} from "vue"
import {listComment, getComment, delComment, addComment, updateComment} from "@/api/bk/comment.js";
import {ElNotification} from 'element-plus'
import {RefreshRight} from '@element-plus/icons-vue'
import md5 from 'md5'

const formRef = ref(null);

const props = defineProps({
  id: {
    type: String,
    required: true
  }
});

const commentList = ref([]);
const loading = ref(false);
const total = ref(0);
// 新增响应式数据
const lastSubmitTime = ref(0)
const captchaQuestion = ref('')
const correctCaptchaAnswer = ref(0)
const userCaptchaAnswer = ref('')
const countdown = ref(0)
let timer = null

// 默认头像URL
const DEFAULT_AVATAR = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

// 获取头像URL
const getAvatarUrl = (email) => {
  if (!email) return DEFAULT_AVATAR

  // 使用Gravatar服务获取头像
  const emailHash = md5(email.trim().toLowerCase())
  return `https://cravatar.cn/avatar/${emailHash}?d=identicon&s=80`
}

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  commentId: null,
  articleId: null,
  content: null,
  authorEmail: null,
  authorWebsite: null,
  commentStatus: 0,
  parentId: null,
  floor: null,
  createTime: null,
  parentFloor: null,
})
const fromNode = ref({
  parentFloor: null,
  articleId: null,
  parentId: null,
  authorEmail: null,
  authorWebsite: null,
  content: null,
  commentStatus: 1,
})
// 生成验证码方法
const generateCaptcha = () => {
  const operators = ['+', '-']
  const operator = operators[Math.floor(Math.random() * operators.length)]
  let num1 = Math.floor(Math.random() * 10) + 1
  let num2 = Math.floor(Math.random() * 10) + 1

  // 处理减法结果不为负数
  if (operator === '-' && num1 < num2) {
    [num1, num2] = [num2, num1]
  }

  correctCaptchaAnswer.value = operator === '+'
      ? num1 + num2
      : num1 - num2

  captchaQuestion.value = `${num1} ${operator} ${num2} = ?`
  userCaptchaAnswer.value = '' // 清空用户输入
}
// 初始化验证码
onMounted(() => {
  generateCaptcha()
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})

// 校验规则
const rules = reactive({
  authorEmail: [
    {required: true, message: '邮箱不能为空', trigger: 'blur'},
    {type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change']}
  ],
  content: [
    {required: true, message: '评论内容不能为空', trigger: 'blur'},
    {min: 3, message: '评论内容至少3个字符', trigger: 'blur'}
  ],
  authorWebsite: [
    {
      validator: (rule, value, callback) => {
        if (value && !/^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/.test(value)) {
          callback(new Error('请输入有效的网址'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
});

// 提交表单
const submit = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return

    // 验证验证码
    if (parseInt(userCaptchaAnswer.value) !== correctCaptchaAnswer.value) {
      ElNotification({
        title: '验证失败',
        type: 'warning',
        duration: 2000,
        message: '验证码计算错误，请重新计算',
      })
      generateCaptcha()
      return
    }

    // 时间间隔验证
    const now = Date.now()
    const remaining = Math.ceil((50000 - (now - lastSubmitTime.value)) / 1000)

    if (remaining > 0) {
      ElNotification({
        title: '提交频率限制',
        type: 'info',
        duration: 2000,
        message: `请${remaining}秒后再提交评论`,
      })
      return
    }

    // 执行提交
    await submitForm()

    // 重置计时
    lastSubmitTime.value = now
    startCountdown()
    generateCaptcha()
  })
}
// 倒计时处理
const startCountdown = () => {
  countdown.value = 50
  if (timer) clearInterval(timer)
  timer = setInterval(() => {
    countdown.value -= 1
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

/** 提交 */
function submitForm() {
  return addComment(fromNode.value).then(response => {
    if (response.code === 200) {
      ElNotification({
        title: '评论成功',
        type: 'success',
        duration: 2000,
        message: '您的评论已提交，需要等待审核通过后显示',
      })
      formRef.value.resetFields()
    }
    queryNo();
    getList();
  }).catch(error => {
    ElNotification({
      title: '评论失败',
      type: 'error',
      duration: 2000,
      message: '提交评论时出现错误，请稍后重试',
    })
  });
}

const queryNo = () => {
  fromNode.value = {
    content: null,
    authorWebsite: null,
    parentId: null,
    parentFloor: null,
    authorEmail: null,
    commentStatus: 1,
  }
}

// 回复
const HuiFu = (id, pf) => {
  fromNode.value.parentId = id
  fromNode.value.parentFloor = pf
  // 滚动到表单
  const formElement = document.getElementById('commentForm');
  if (formElement) {
    formElement.scrollIntoView({
      behavior: 'smooth',  // 平滑滚动
      block: 'start'       // 对齐到视口顶部
    });
  }
}

/** 查询文章评论列表 */
function getList() {
  loading.value = true;
  queryParams.value.articleId = props.id;
  fromNode.value.articleId = props.id;
  listComment(queryParams.value).then(response => {
    commentList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
}

/** 页面变动事件 */
const handleCurrentChange = (newPage) => {
  queryParams.value.pageNum = newPage
  getList()
}

const handleAvatarClick = (url) => {
  if (!url) return;
  // 确保 URL 有 http 前缀
  const fullUrl = url.startsWith('http') ? url : `https://${url}`;
  window.open(fullUrl, '_blank', 'noopener,noreferrer')
}

// 初始化获取评论列表
getList()
</script>

<style lang="scss" scoped>
.comment-count {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 0.2rem;
  margin-top: 0.2rem;
}

.comment-container {
  width: 100%;
  margin: 0 auto;
}

.comment-card {
  width: 100%;
  border-radius: 12px;
  background-color: rgba(244, 244, 244, 0.95);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  }
}

/* 卡片头部 */
.card-header {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  padding: 16px 0;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;

  &::after {
    content: '';
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 3px;
    background-color: #409eff;
    border-radius: 3px;
  }
}

/* 评论列表样式 */
.comment-item {
  margin-bottom: 28px;
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 用户信息区域 */
.user-info {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  margin: 16px 0 8px;
  padding: 0 16px;

  .avatar {
    flex-shrink: 0;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    cursor: pointer;
    transition: all 0.3s ease;
    border: 2px solid transparent;

    &:hover {
      transform: scale(1.05);
      border-color: #409eff;
    }
  }

  .meta {
    flex: 1;

    .floor-tag {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-bottom: 6px;

      .tag {
        border-radius: 16px;
        padding: 0 12px;
        height: 26px;
        line-height: 24px;
        font-weight: 500;
      }
    }

    .time {
      font-size: 12px;
      color: #909399;
    }
  }
}

/* 评论内容卡片 */
.comment-content {
  margin: 0 16px 12px 40px;
  border-radius: 12px;
  background: #fff;
  transition: all 0.3s ease;
  cursor: pointer;

  &:hover {
    transform: translateX(4px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    background-color: #f8f9fa;
  }

  :deep(.el-card__body) {
    padding: 16px;
    font-size: 14px;
    line-height: 1.6;
    color: #34495e;
    text-align: left;

    @media (max-width: 768px) {
      padding: 12px;
    }
  }
}

/* 分页容器 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;

  :deep(.el-pagination) {
    .el-pagination__jump {
      margin-left: 16px;
    }

    .btn-prev,
    .btn-next,
    .number {
      border-radius: 6px;
      transition: all 0.2s;
      margin: 0 3px;

      &:hover {
        transform: translateY(-2px);
      }
    }

    .el-pager .number.is-active {
      background-color: #409eff;
      color: white;
      font-weight: 600;
    }
  }
}

/* 评论表单区域 */
.comment-form {
  padding: 20px 16px;
  background-color: rgba(255, 255, 255, 0.6);
  border-radius: 12px;
  margin-top: 8px;

  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #2c3e50;
  }

  :deep(.el-input),
  :deep(.el-textarea) {

    .el-input__wrapper,
    .el-textarea__inner {
      border-radius: 8px;
      transition: all 0.3s;

      &:focus {
        box-shadow: 0 0 0 1px #409eff inset;
      }
    }
  }

  .reply-tag {
    height: 32px;
    display: flex;
    align-items: center;

    .el-tag {
      height: 28px;
      line-height: 26px;
      border-radius: 14px;
    }
  }
}

/* 验证码区域 */
.captcha-container {
  display: flex;
  align-items: center;
  gap: 12px;

  .captcha-input {
    width: 120px;
    flex-shrink: 0;
  }

  .captcha-question {
    font-weight: 600;
    color: #409eff;
    font-size: 16px;
    user-select: none;
    background-color: rgba(64, 158, 255, 0.1);
    padding: 6px 12px;
    border-radius: 8px;
  }

  .refresh-captcha {
    padding: 0;
    height: auto;
    color: #909399;

    &:hover {
      color: #409eff;
    }
  }
}

/* 表单底部 */
.form-footer {
  margin-top: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;

  .submit-btn {
    min-width: 120px;
    border-radius: 20px;
    padding: 10px 20px;
    font-weight: 500;
    transition: all 0.3s;

    &:not([disabled]):hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
    }
  }

  .tip-text {
    margin-top: 16px;
    color: #606266;
    font-size: 13px;
    line-height: 1.5;
    text-align: left;
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .comment-container {
    width: 100%;
  }

  .comment-card {
    width: 100%;
  }

  .comment-content {
    margin-left: 16px;
  }

  .user-info {
    padding: 0 10px;
    gap: 10px;

    .meta .floor-tag {
      flex-wrap: wrap;
      gap: 6px;
    }
  }

  .comment-form {
    padding: 16px 10px;
  }

  .captcha-container {
    flex-wrap: wrap;

    .captcha-input {
      width: 100%;
    }
  }
}
</style>